package com.atguigu.crowd.util;


import com.atguigu.crowd.constant.CrowdConstant;

import javax.servlet.http.HttpServletRequest;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 异常映射
 */
public class CrowdUtil {
    /**
     * 判断当前请求是否为Ajax请求
     *
     * @param request
     * @return
     */
    public static boolean judgeRequestType(HttpServletRequest request) {
        // 1.获取请求消息头信息
        String acceptInformation = request.getHeader("Accept");
        String xRequestInformation = request.getHeader("X-Requested-With");
        // 2.检查并返回
        return
                (acceptInformation != null && acceptInformation.length() > 0 && acceptInformation.contains("application/json"))
                        ||
                        (xRequestInformation != null && xRequestInformation.length() > 0 && xRequestInformation.equals("XMLHttpRequest"));
    }

    /**
     * MD5加密算法
     * @param source 传入的明文字符串
     * @return 加密结果
     */

    public static String md5(String source){
        if(source == null || source.length() == 0){
            //如果不是有效的字符串抛出异常
            throw new RuntimeException(CrowdConstant.MESSAGE_STRING_INVALIDATE);
        }

        try {
            String algorithm = "md5"; // 加密算法的类型
            MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
            byte[] input = source.getBytes();
            //5.执行加密
            byte[] output = messageDigest.digest(input);
            int signum = 1;
            //6.创建BigInteger对象 1正 -1负
            BigInteger bigInteger = new BigInteger(signum,output);
            //7.按照 16 进制将 bigInteger 的值转换为字符串
            int radix = 16;
            String encode = bigInteger.toString(radix).toUpperCase();
            return  encode;
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }

    }

    public static void main(String[] args) {
        System.out.println(md5("123456"));
    }
}
